package com.example.onlinemusic.controller;

import com.example.onlinemusic.model.User;
import com.example.onlinemusic.service.UserService;
import com.example.onlinemusic.tools.Constant;
import com.example.onlinemusic.tools.ResponseBodyMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = "/user")
@ResponseBody
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @RequestMapping(value = "/login")
    public ResponseBodyMessage<User> login(HttpServletRequest request,@RequestParam String username
    ,@RequestParam String password){

        User user = userService.selectByName(username);
        if(user == null){
            return new ResponseBodyMessage<>(-1,"用户名或者密码错误",user);
        }else {
            Boolean flg = bCryptPasswordEncoder.matches(password, user.getPassword());
            if(!flg){
                return new ResponseBodyMessage<>(-1,"用户名或者密码错误",user);
            }
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user);
            return new ResponseBodyMessage<>(0,"登陆成功",user);
        }
    }

}
